package client_tests;

import net.es.lookup.client.QueryClient;
import net.es.lookup.client.SimpleLS;
import net.es.lookup.common.exception.LSClientException;
import net.es.lookup.common.exception.ParserException;
import net.es.lookup.common.exception.QueryException;
import net.es.lookup.queries.Query;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * Created with IntelliJ IDEA.
 * User: luke
 * Date: 8/5/13
 * Time: 4:07 PM
 * To change this template use File | Settings | File Templates.
 */
public class SingleQuery implements ScalabilityTest {

    private ResultTransmitter rx;
    private SimpleLS sls;
    private QueryClient qc;
    private String sourceHost;

    public SingleQuery() {

    }

    @Override
    public void initialize(String targetHost, int port, String sourceHost, int op_interval, int numThreads, int testRounds) throws LSClientException {

        rx = new ResultTransmitter();
        sls = new SimpleLS(targetHost, port);
        qc = new QueryClient(sls);
        this.sourceHost = sourceHost;
    }

    @Override
    public void runTest() {

        String timestamp = null;
        long testStart = 0;
        long testFinish = 0;
        try {

            DateFormat df = new SimpleDateFormat("MM-dd-HH-mm-ss");

            testStart = System.currentTimeMillis();
            timestamp = df.format(testStart);
            System.out.println(testStart + ": starting query with no parameters");
            qc.setQuery(new Query());
            qc.query();
            testFinish = System.currentTimeMillis();
            System.out.println(testFinish + ": query finished after " + (testFinish - testStart) / 1000 + " seconds");

            rx.add(sourceHost + "-0:" + timestamp, sls.getConnectionType(), Long.toString(testFinish - testStart), Integer.toString(sls.getResponseCode()));


        } catch (LSClientException e) {

            rx.add(sourceHost + "-0-" + timestamp, sls.getConnectionType(),
                    Long.toString(testFinish - testStart), e.getMessage());
        } catch (ParserException e) {

            rx.add(sourceHost + "-0-" + timestamp, sls.getConnectionType(),
                    Long.toString(testFinish - testStart), e.getMessage());
        } catch (QueryException e) {

            rx.add(sourceHost + "-0-" + timestamp, sls.getConnectionType(),
                    Long.toString(testFinish - testStart), e.getMessage());
        }
    }

    @Override
    public void printResults() {

        rx.print();
    }
}
